﻿using Blazui.Component;
using Microsoft.AspNetCore.Components;
using Microsoft.EntityFrameworkCore;
using Project13776616780_01.Model;
using Project13776616780_01.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Project13776616780_01.Pages
{
    public partial class Products
    {
        [Inject]
        DocsDbContext dbContext { get; set; }
        [Inject]
        private DialogService dialogService { get; set; }
        private string searchTitle;
        private int categoryId;
        private List<ProductModel> products = new List<ProductModel>();

        private HashSet<object> selectedProducts = new HashSet<object>();
        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();
            RefreshData();
        }

        private void Search()
        {
            RefreshData(false);
        }

        private async Task BeginEditAsync(object row)
        {
            var productModel = row as ProductModel;
            var updateProductModel = new UpdateProductModel()
            {
                Id = productModel.Id,
                Author = new KeyValuePair<int, string>(productModel.AuthorId, productModel.Author),
                Category = new KeyValuePair<int, string>(productModel.CategoryId, "加载中..."),
                Description = productModel.Description,
                Company = new KeyValuePair<int, string>(productModel.CompanyId, "加载中..."),
                DescriptionTitle = productModel.DescriptionTitle,
                Image = new IFileModel[]
                   {
                       new UploadModel()
                       {
                            Url=productModel.Image,
                            FileName=System.IO.Path.GetFileName(productModel.Image)
                       }
                   },
                CreationTime = productModel.CreationTime,
                Name = productModel.Name,
                Size = new KeyValuePair<int, string>(productModel.SizeId, "加载中...")
            };
            var parameters = new Dictionary<string, object>();
            parameters.Add(nameof(UpdateProduct.Product), updateProductModel);
            var r = await dialogService.ShowDialogAsync<UpdateProduct, bool>("更新藏品", parameters);
            if (!r.Result)
            {
                return;
            }
            RefreshData();
        }

        private void RefreshData(bool autoRefresh = true)
        {
            var query = dbContext.Set<Product>().Where(x => !x.IsDeleted);
            if (!string.IsNullOrWhiteSpace(searchTitle))
            {
                query = query.Where(x => x.Name.Contains(searchTitle));
            }
            if (categoryId > 0)
            {
                query = query.Where(x => x.CategoryId == categoryId);
            }
            var authors = dbContext.Authors.ToDictionary(x => x.Id, x => x.Name);
            var sizes = dbContext.Sizes.ToDictionary(x => x.Id, x => x.Name);
            products = query.OrderByDescending(x => x.Id).Select(x => new ProductModel()
            {
                Author = authors.GetValueOrDefault(x.AuthorId, "未知"),
                CreationTime = x.CreationTime,
                IdNumber = x.IdNumber,
                Image = x.Image,
                Name = x.Name,
                Id = x.Id,
                SizeId = x.SizeId,
                AuthorId = x.AuthorId,
                Size = sizes.GetValueOrDefault(x.SizeId, "未知"),
                Description = x.Description,
                DescriptionTitle = x.DescriptionTitle,
                CompanyId = x.CompanyId,
                CategoryId = x.CategoryId
            }).ToList();
            if (!autoRefresh)
            {
                return;
            }
            _ = InvokeAsync(Refresh);
        }

        private async Task DeleteAsync()
        {
            if (!selectedProducts.Any())
            {
                Toast("没有选择任何藏品");
                return;
            }
            foreach (ProductModel item in selectedProducts)
            {
                var ep = dbContext.Set<Product>().FirstOrDefault(x => x.Id == item.Id);
                if (ep == null)
                {
                    continue;
                }
                ep.IsDeleted = true;
            }
            await dbContext.SaveChangesAsync();
            RefreshData();
            Toast("已移进回收站");
        }

        private async Task ShowCreateWindowAsync()
        {
            var r = await dialogService.ShowDialogAsync<UpdateProduct, bool>("添加藏品", new Dictionary<string, object>());
            if (!r.Result)
            {
                return;
            }
            RefreshData();
        }

        protected override bool ShouldRender()
        {
            return true;
        }
    }
}
